<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 4/11 0011
 * Time: 17:01
 */

namespace app\index\model;

use think\Model;
use think\Session;

class Eleorder extends Model{

    /**
     * 获取手机列表反序列化
     * @param $value
     * @return mixed
     */
    public function getPhonelist($value){
        return unserialize($value);
    }

    /**
     * 饿了么数据更新到数据库中
     * TODO 订单状态变更消息 部分接收不到
     */
    public function updatedata(){
        //TODO 验签
        $postdata=file_get_contents("php://input");//POST数据
        if ($postdata == null) {
            return false;
        }
        //转换message
        $verifymessage = self::convert_to_message($postdata);
        //校验签名
        $result = self::check_signature($verifymessage,"bc1c1d3512a7da61dad819f115fb165f");
        if(!$result){
            file_put_contents(RUNTIME_PATH."log/ele/验签失败".time().".txt","get:".serialize(request()->get()).PHP_EOL."post:".serialize(request()->post()));//记录日志
            return false;//签名验证失败
        }
        //开始转化成大数组
        $message=json_decode($verifymessage["message"],true,512,JSON_BIGINT_AS_STRING);//将message字符串转换成关联数组
        $res=true;
        switch ($verifymessage["type"]){
            //订单生效
            case 10:
                $res=$this->save([
                    "orderid"=>$message['orderId'],
                    "address"=>$message['address'],
                    "createdat"=>$message['createdAt'],
                    "activeat"=>$message['activeAt'],
                    "deliverfee"=>$message['deliverFee'],
                    "delivertime"=>$message['deliverTime'],
                    "description"=>$message['description'],
                    "groups"=>serialize($message['groups']),
                    "invoice"=>$message['invoice'],
                    "book"=>$message['book'],
                    "onlinepaid"=>$message['onlinePaid'],
                    "railwayaddress"=>$message['railwayAddress'],
                    "phonelist"=>serialize($message['phoneList']),
                    "shopid"=>$message['shopId'],
                    "shopname"=>$message['shopName'],
                    "daysn"=>$message['daySn'],
                    "status"=>$message['status'],
                    "refundstatus"=>$message['refundStatus'],
                    "userid"=>$message['userId'],
                    "totalprice"=>$message['totalPrice'],
                    "originalprice"=>$message['originalPrice'],
                    "consignee"=>$message['consignee'],
                    "deliverypoiaddress"=>$message['deliveryPoiAddress'],
                    "invoiced"=>$message['invoiced'],
                    "income"=>$message['income'],
                    "servicerate"=>$message['serviceRate'],
                    "servicefee"=>$message['serviceFee'],
                    "hongbao"=>$message['hongbao'],
                    "packagefee"=>$message['packageFee'],
                    "activitytotal"=>$message['activityTotal'],
                    "shoppart"=>$message['shopPart'],
                    "elemepart"=>$message['elemePart'],
                    "downgraded"=>$message['downgraded']
                ]);
                break;
//            商户接单
            case 12:
                $res=$this->save([
                    "status"=>$message['state']
                ],["orderid"=>$message['orderId']]);
                break;
//                订单被取消
            case 14:
                $res=$this->save([
                    "status"=>$message['state']
                ],["orderid"=>$message['orderId']]);
                break;
                //订单置为无效
            case 15:
                $res=$this->save([
                    "status"=>$message['state']
                ],["orderid"=>$message['orderId']]);
                break;
                //订单强制无效
            case 17:
                $res=$this->save([
                    "status"=>$message['state']
                ],["orderid"=>$message['orderId']]);
                break;
//                订单完结
            case 18:
                $res=$this->save([
                    "status"=>$message['state']
                ],["orderid"=>$message['orderId']]);
                break;
//                用户申请取消单
            case 20:
                break;
//                用户取消取消单申请
            case 21:
                break;
//                商户拒绝取消单
            case 22:
                break;
//                用户同意取消单
            case 23:
                break;
//                用户申请仲裁
            case 24:
                break;
//                客服仲裁取消单申请有效
            case 25:
                break;
//                客服仲裁退单申请无效
            case 26:
                break;
//                用户申请退单
            case 30:
                break;
//                用户取消退单
            case 31:
                break;
//                商户拒绝退单
            case 32:
                break;
//                商户同意退单
            case 33:
                break;
//                用户申请仲裁
            case 34:
                break;
//                客服仲裁退单有效
            case 35:
                break;
//                客服仲裁退单无效
            case 36:
                break;
//                用户催单
            case 45:
                break;
//                商家回复用户催单
            case 46:
                break;
//                待分配配送商
            case 51:
                break;
//                待分配配送员
            case 52:
                break;
//                配送员取餐中
            case 53:
                break;
//                配送员已到店
            case 54:
                break;
//                配送员配送中
            case 55:
                break;
//                配送成功
            case 56:
                break;
//                配送取消,商户取消
            case 57:
                break;
//                配送取消,用户取消
            case 58:
                break;
//                配送取消,物流系统取消
            case 59:
                break;
                //配送失败,呼叫配送晚
            case 60:
                break;
//                配送失败,餐厅出餐问题
            case 61:
                break;
//                配送失败,商户终端配送
            case 62:
                break;
//                配送失败,用户不接电话
            case 63:
                break;
//                配送失败,用户退单
            case 64:
                break;
//                配送失败,用户地址错误
            case 65:
                break;
//                配送失败,超出服务范围
            case 66:
                break;
//                配送失败,骑手标记异常
            case 67:
                break;
//                配送失败,系统自动标记异常
            case 68:
                break;
//                配送失败,其他异常
            case 69:
                break;
//                配送失败,超时标记异常
            case 70:
                break;
//                自行配送
            case 71:
                break;
//                不再配送
            case 72:
                break;
//                物流拒单,仅支持在线支付
            case 73:
                break;
//                物流拒单,超出服务范围
            case 74:
                break;
//                物流巨单,请求配送晚
            case 75:
                break;
//                物流拒单,系统异常
            case 76:
                break;
//                店铺营业状态变化
            case 91:
                break;
//                店铺状态变更消息
            case 92:
                break;
            default:
                $res=true;
        }
        return $res;
    }

    /**
     * JSON_DECODE
     * @param $content
     * @return mixed
     */
    public static function convert_to_message($content)
    {
        try {
            $message = json_decode($content, true,512,JSON_BIGINT_AS_STRING);
        } catch (\Exception $e) {
            throw new \Exception("convert content to message error.");
        }
        return $message;
    }

    /**
     * 检查签名
     * @param $message
     * @param $secret
     * @return bool
     */
    public static function check_signature($message, $secret)
    {
        $params = $message;
        $signature = $message["signature"];
        unset($params["signature"]);
        if ($signature != self::get_signature($params, $secret)) {
            return false;
        }
        return true;
    }

    /**
     * 获取签名
     * @param array $param
     * @param $secret
     * @return string
     */
    public static function get_signature(array $param, $secret)
    {
        ksort($param);
        $string = "";
        foreach ($param as $key => $value) {
            $string .= $key . "=" . $value;
        }
        $splice = $string . $secret;
        $md5 = strtoupper(md5($splice));
        return $md5;
    }

    /**
     * 获取指定条件的订单数据
     * @param $condition 查询条件
     */
    public function getorder($condition){
        $where="1";
        if(!empty($condition["status"])){
            $arr=explode(",",$condition["status"]);
            $arr=array_map(function($v){return "'".$v."'";},$arr);
            $where.=" and status in (".implode(",",$arr).")";
        }
        if(!empty($condition["starttime"])){
            $where.=" and activeat>='".$condition["starttime"]." 00:00:00'";
        }
        if(!empty($condition["endtime"])){
            $where.=" and activeat<='".$condition["endtime"]." 23:59:59'";
        }
        if(!empty($condition["keyword"])){
            $where.=" and orderid='".$condition["keyword"]."'";
        }
        $elelink=new Elelink();
        $res=$elelink->where("shopid",Session::get("shopid"))->where("updatetime+expiresin>".time())->find();
        $data=$this->where($where)->whereIn("shopid",$res["authorizedshops"])->select();
        foreach ($data as $k=>$v){
            $data[$k]["groups"]=unserialize($v["groups"]);
            $data[$k]["phonelist"]=unserialize($v["phonelist"]);
        }
        return $data;
    }

}